package com.talos.ums.service.usercustomer;

import com.talos.framework.common.pojo.PageResult;
import com.talos.framework.common.util.object.BeanUtils;
import com.talos.ums.controller.admin.usercustomer.vo.UmsUserCustomerPageReqVO;
import com.talos.ums.controller.admin.usercustomer.vo.UmsUserCustomerSaveReqVO;
import com.talos.ums.dal.dataobject.usercustomer.UmsUserCustomerDO;
import com.talos.ums.dal.mysql.usercustomer.UmsUserCustomerMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import static com.talos.framework.common.exception.enums.GlobalErrorCodeConstants.DATA_NOT_FOUND;
import static com.talos.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 账号关联客户表 Service 实现类
 *
 * @author ${table.author}
 */
@Service
@Validated
public class UmsUserCustomerServiceImpl implements UmsUserCustomerService {

    @Resource
    private UmsUserCustomerMapper userCustomerMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createUserCustomer(UmsUserCustomerSaveReqVO createReqVO) {
        // 插入
        UmsUserCustomerDO userCustomer = BeanUtils.toBean(createReqVO, UmsUserCustomerDO.class);
        userCustomerMapper.insert(userCustomer);
        // 返回
        return userCustomer.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserCustomer(UmsUserCustomerSaveReqVO updateReqVO) {
        // 校验存在
        validateUserCustomerExists(updateReqVO.getId());
        // 更新
        UmsUserCustomerDO updateObj = BeanUtils.toBean(updateReqVO, UmsUserCustomerDO.class);
        userCustomerMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserCustomer(Long id) {
        // 校验存在
        validateUserCustomerExists(id);
        // 删除
        userCustomerMapper.deleteById(id);
    }

    private void validateUserCustomerExists(Long id) {
        if (userCustomerMapper.selectById(id) == null) {
            throw exception(DATA_NOT_FOUND);
        }
    }

    @Override
    public UmsUserCustomerDO getUserCustomer(Long id) {
        return userCustomerMapper.selectById(id);
    }

    @Override
    public PageResult<UmsUserCustomerDO> getUserCustomerPage(UmsUserCustomerPageReqVO pageReqVO) {
        return userCustomerMapper.selectPage(pageReqVO);
    }

}
